home *** CD-ROM | disk | FTP | other *** search
- Path: atglab.bls.com!Alun.Champion
- From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: 19 Jan 1996 22:01:41 GMT
- Organization: Computer People Inc.
- Message-ID: <ALUN.CHAMPION.96Jan19170141@g7240065.bridge.bst.bls.com>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>
- <4dorr8$i58@cloner3.netcom.com>
- NNTP-Posting-Host: bstfirewall.bst.bls.com
- In-reply-to: a1s@ix.netcom.com's message of Fri, 19 Jan 1996 22:33:52 GMT
-
- In article <4dorr8$i58@cloner3.netcom.com> a1s@ix.netcom.com (Andrew Snyder) writes:
-
- : Bill Simpson <wsimpson@uwinnipeg.ca> wrote:
-
- :> Is there a fast way to decide whether a number n is a power of 2?
-
- :> The only thing I have thought of is that if n is power of 2
- :> log(n)/log(2) is an integer
- :> BUT this is going to be a SLOW computation. Needs to be fast.
-
- :> Since I am dealing with unsigned long ints, I guess I can just store all
- :> 31 powers of 2 in a table and compare to n. Though I don't know a fast
- :> algorithm to compare a number to 31 numbers in an array.
-
- :> Perhaps there is a tricky nonportable way to see if I have power-of-2 by
- :> looking at bits? (That is fine for this application)
-
- : no tricks
-
- : #define ISPOW2(x) (((x) & 1) ^ 1)
-
- This doesn't answer his question - all this tells him is if x is even
- (i.e: x % 2 == 0)
-
- You could try:
-
- #include <limits.h>
-
- int
- ispow2(unsigned long x)
- {
- int i;
-
- for (i = 1; i < sizeof(x) * CHAR_BIT; i++)
- if ((x ^ (1 << i)) == 0)
- return 1;
-
- return 0;
- }
-
- Hope this helps
- Regards
-
- -A.
-
-
-
-
-
-
-
-
-
-
-
- --
- | A.Champion |
-